package com.kingdee.pda.ui.fast_allot;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;

import com.example.basecommon.http.MyObserver;
import com.example.basecommon.http.RxHelper;
import com.example.basecommon.http.rxjava.BaseResponse;
import com.example.basecommon.http.rxjava.HttpUtils;
import com.example.basecommon.utils.ConstantUtil;
import com.example.basecommon.utils.SpeakUtils;
import com.kingdee.pda.Api;
import com.kingdee.pda.R;
import com.kingdee.pda.entity.FastAllotRequestBean;
import com.kingdee.pda.entity.QtfInOutEntryInfoRequest;
import com.kingdee.pda.entity.Warehouse;
import com.kingdee.pda.ui.activity.BaseTitleActivity;
import com.kingdee.pda.ui.popupwindow.ListSelectorPpWindow;
import com.kingdee.pda.ui.widget.CleanableEditText;
import com.kingdee.pda.util.CommonUtil;
import com.kingdee.pda.util.WarehouseUtil;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * 快速调拨选择仓库货主
 * Created by dlj
 * DATE 2021/9/3
 * TIME 13:25
 */
public class FastAllotSelectWarehouseActivity extends BaseTitleActivity implements View.OnKeyListener, View.OnClickListener {

    private EditText et_outWarehouse;
    private EditText et_inWarehouse;
    private EditText et_outOwner;
    private EditText et_inOwner;
    private ImageView iv_inWarehouse, iv_outOwner, iv_inOwner;
    private LinearLayout ll_inWarehouse, ll_outOwner, ll_inOwner;
    private RadioButton rb_1;

    private Warehouse outOwner;
    private Warehouse inWarehouse;

    private Button btn_next;
    private ListSelectorPpWindow<Warehouse> outOwnerSelector;
    private ListSelectorPpWindow<Warehouse> inWarehouseSelector;
    private List<Warehouse> orgList = new ArrayList<>();
    private List<QtfInOutEntryInfoRequest> goodList = new ArrayList<>();

    private boolean isShowSelecter = true;

    public static void actionStart(Context context) {
        context.startActivity(new Intent(context, FastAllotSelectWarehouseActivity.class));
    }

    @Override
    protected void onActivityCreate(Bundle savedInstanceState) {
        super.onActivityCreate(savedInstanceState);
        setContentView(R.layout.activity_fast_allot_select);
    }

    @Override
    protected void initView() {
        super.initView();
        setTitle("快速调拨");

        et_outWarehouse = findViewById(R.id.et_outWarehouse);
        et_inWarehouse = findViewById(R.id.et_inWarehouse);
        et_outOwner = findViewById(R.id.et_outOwner);
        et_inOwner = findViewById(R.id.et_inOwner);

        setEditTextScannerEvents(et_outWarehouse, this);
        setEditTextScannerEvents(et_inWarehouse, this);
        setEditTextScannerEvents(et_outOwner, this);
        setEditTextScannerEvents(et_inOwner, this);

        ll_inWarehouse = findViewById(R.id.ll_inWarehouse);
        ll_outOwner = findViewById(R.id.ll_outOwner);
        ll_inOwner = findViewById(R.id.ll_inOwner);

        btn_next = findViewById(R.id.btn_next);
        iv_inWarehouse = findViewById(R.id.iv_inWarehouse);
        iv_outOwner = findViewById(R.id.iv_outOwner);
        iv_inOwner = findViewById(R.id.iv_inOwner);

        rb_1 = findViewById(R.id.rb_1);

        btn_next.setOnClickListener(this);
        iv_inWarehouse.setOnClickListener(this);
        iv_outOwner.setOnClickListener(this);
        iv_inOwner.setOnClickListener(this);

        initEditTextListener();

        WarehouseUtil.getOnlineWarehouseList(this);//重新拉取一遍仓库列表

        getOrgList();
    }

    /**
     * 获取单位组织（货主）列表
     */
    private void getOrgList() {
        HashMap<String, Object> map = new HashMap<>();
        MyObserver<List<Warehouse>> myObserver = new MyObserver<List<Warehouse>>(this) {
            @Override
            public void onSuccess(BaseResponse<List<Warehouse>> result) {
                orgList.clear();
                for (Warehouse org : result.data) {
                    if (org.isFisaccounting()) {
                        orgList.add(org);
                    }
                }

                reflushData();
            }

            @Override
            public void onFailure(BaseResponse result, String msg) {
                SpeakUtils.speakWithToast(FastAllotSelectWarehouseActivity.this, msg, false, false);
            }
        };
        HttpUtils.request(Api.class)
                .getWarehouseList(ConstantUtil.GET_ORG_LIST, map)
                .compose(RxHelper.observableIO2Main(this))
                .subscribe(myObserver);
    }

    @Override
    protected void initData() {
        super.initData();
    }

    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if (!(v instanceof EditText)) {
            return false;
        }
        EditText editText = (EditText) v;
        String input = editText.getText().toString().trim();
        if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) {
            switch (v.getId()) {
                case R.id.et_outWarehouse:
                    break;
                case R.id.et_skuCode:
                    break;
                case R.id.et_inLocationcode:
                    break;
            }
            return true;
        }
        return false;
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.iv_inWarehouse:
                List<Warehouse> warehouseList = WarehouseUtil.getWarehouseList();
                showInWarehouseSelector(warehouseList);
                break;
            case R.id.iv_outOwner:
                if (orgList != null)
                    showoutOwnerSelector(orgList);
                break;
            case R.id.iv_inOwner:
                break;
            case R.id.btn_next:
                if (checkDataValid()) {
                    Intent intent = new Intent(this, FastAllotOperateActivity.class);
                    intent.putExtra("outOwner", outOwner);
                    intent.putExtra("inWarehouse", inWarehouse);
                    intent.putExtra("scanStyle", rb_1.isChecked() ? 0 : 1);
                    if (goodList != null)
                        intent.putExtra("goodList", (Serializable) goodList);
                    startActivityForResult(intent, 1000);
                }
                break;
        }
    }

    private void reflushData() {
        try {
            Warehouse currentWarehouse = WarehouseUtil.getCurrentWarehouse();
            et_outWarehouse.setText(currentWarehouse.getName());
            if (!TextUtils.isEmpty(currentWarehouse.getOrgname())) {//如果有默认管理组织
                outOwner = new Warehouse(currentWarehouse.getOrg(), currentWarehouse.getOrgname());
                isShowSelecter = false;
                et_outOwner.setText(currentWarehouse.getOrgname());
                isShowSelecter = true;
                et_inOwner.setText(currentWarehouse.getOrgname());
            }
            CommonUtil.requestFocusAndClearText(et_inWarehouse);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 展示调入仓库选择框
     */
    private void showInWarehouseSelector(List<Warehouse> list) {
        if (inWarehouseSelector != null) inWarehouseSelector.dismiss();
        inWarehouseSelector = new ListSelectorPpWindow<Warehouse>(FastAllotSelectWarehouseActivity.this,
                R.drawable.shape_bg_edit_selected,
                ll_inWarehouse.getWidth(),
                list, new ListSelectorPpWindow.onItemSelectedListener() {
            @Override
            public void onItemSelected(Object item) {
                Warehouse dataBean = (Warehouse) item;
                if (dataBean.getId() == getCurrentWarehouse().getId()) {
                    SpeakUtils.speakWithToast(FastAllotSelectWarehouseActivity.this, "调入、调出仓库不能相同", false, false);
                    return;
                }
                isShowSelecter = false;
                et_inWarehouse.setText(dataBean.getName());
                isShowSelecter = true;//此操作是为了防止et_outOwner触发TextWatcher，又显示一遍弹框
                inWarehouse = dataBean;
                checkDataValid();
                CommonUtil.requestFocusAndNoClearText(et_outOwner);

                //切换选择之后清空记录的商品列表
                goodList.clear();
            }
        });

        inWarehouseSelector.showAsDropDown(ll_inWarehouse, 0, 10);
    }

    /**
     * 展示调出货主选择框
     */
    private void showoutOwnerSelector(List<Warehouse> list) {
        if (outOwnerSelector != null) outOwnerSelector.dismiss();
        outOwnerSelector = new ListSelectorPpWindow<Warehouse>(FastAllotSelectWarehouseActivity.this,
                R.drawable.shape_bg_edit_selected,
                ll_outOwner.getWidth(),
                list, new ListSelectorPpWindow.onItemSelectedListener() {
            @Override
            public void onItemSelected(Object item) {
                Warehouse dataBean = (Warehouse) item;
                outOwner = dataBean;
                isShowSelecter = false;
                et_outOwner.setText(dataBean.getName());
                CommonUtil.requestFocusAndNoClearText(et_outOwner);
                isShowSelecter = true;
                et_inOwner.setText(dataBean.getName());
                checkDataValid();

                //切换选择之后清空记录的商品列表
                goodList.clear();
            }
        });
        outOwnerSelector.showAsDropDown(ll_outOwner, 0, 10);
    }

//    @Override
//    public void onFocusChange(View view, boolean b) {
//
//        switch (view.getId()) {
//            case R.id.et_inWarehouse:
//                if (b) {
//                    focusEditText = et_inWarehouse;
//                }
//                ll_inWarehouse.setBackgroundResource(b ? R.drawable.shape_bg_edit_selected : R.drawable.dialog_edit_bg);
//                break;
//            case R.id.et_outOwner:
//                if (b) {
//                    focusEditText = et_outOwner;
//                }
//                ll_outOwner.setBackgroundResource(b ? R.drawable.shape_bg_edit_selected : R.drawable.dialog_edit_bg);
//                break;
//            case R.id.et_inOwner:
//                if (b) {
//                    focusEditText = et_inOwner;
//                }
//                ll_inOwner.setBackgroundResource(b ? R.drawable.shape_bg_edit_selected : R.drawable.dialog_edit_bg);
//                break;
//        }
//    }

    @Override
    public void changeWarehouse(Warehouse warehouse) {
        clearAllView();
        reflushData();
    }


    private boolean checkDataValid() {
        if (inWarehouse != null && outOwner != null) {
            btn_next.setEnabled(true);
            return true;
        } else {
            btn_next.setEnabled(false);
            return false;
        }
    }

    private void clearAllView() {
        et_inWarehouse.setText("");
        et_outOwner.setText("");
        et_inOwner.setText("");

        inWarehouse = null;
        outOwner = null;
        rb_1.setChecked(true);
    }

    public List search(String name, List list) {
        List results = new ArrayList();
        if (list.size() > 0) {
            Pattern pattern = Pattern.compile(name);
            for (int i = 0; i < list.size(); i++) {
                Matcher matcher = pattern.matcher(((Warehouse) list.get(i)).getName());
                if (matcher.find()) {
                    results.add(list.get(i));
                }
            }
        }
        return results;
    }

    private void initEditTextListener() {
        et_inWarehouse.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                String changeText = et_inWarehouse.getText().toString();
                if (!TextUtils.isEmpty(changeText) && isShowSelecter) {
                    List<Warehouse> search = search(changeText, WarehouseUtil.getWarehouseList());
                    showInWarehouseSelector(search);
                }
            }
        });

        et_outOwner.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                String changeText = et_outOwner.getText().toString();
                if (!TextUtils.isEmpty(changeText) && isShowSelecter) {
                    List<Warehouse> search = search(changeText, orgList);
                    showoutOwnerSelector(search);
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 2000 && requestCode == 1000 && data != null) {
            goodList = (List<QtfInOutEntryInfoRequest>) data.getSerializableExtra("goodList");
        }
    }
}
